package com.extension.company.common.mvc;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Lenovo on 2015/5/14.
 */
public abstract class BaseFragment extends Fragment {
	
    protected View contentView;
    private Unbinder unbinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化视图和数据
//        contentView = getActivity().getLayoutInflater().inflate(getMainLayout(), null);
//        unbinder = ButterKnife.bind(this, contentView);
//        init();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        if (contentView==null){
            contentView= getActivity().getLayoutInflater().inflate(getMainLayout(), null);
        }else {
            ViewGroup viewGroup= (ViewGroup) contentView.getParent();
            if (viewGroup!=null){
                viewGroup.removeView(contentView);
            }
        }
        unbinder = ButterKnife.bind(this, contentView);
        init();
        return contentView;//这里是返回的视图

    }

    /**
     * 注册组件
     *
     * @param id
     * @param <T>
     * @return
     */
    protected <T extends View> T getViewById(int id) {
        return (T) contentView.findViewById(id);
    }

    /**
     * 注册组件，基于View
     *
     * @param view
     * @param id
     * @param <T>
     * @return
     */
    protected <T extends View> T getViewById(View view, int id) {
        return (T) view.findViewById(id);
    }

    /**
     * 获得主界面layout资源
     *
     * @return
     */
    public abstract void init();

    /**
     * 获得主界面layout资源
     *
     * @return
     */
    public abstract int getMainLayout();
    
    @Override
    public void onDestroyView() {

        if (unbinder != null) {
            unbinder.unbind();
        }

        super.onDestroyView();
        //在销毁视图的时�?�把父控件remove�??下，不然重新加载的时候会异常导致奔溃，提示should remove parent view
//        ViewGroup mGroup = (ViewGroup) contentView.getParent();
//        if (mGroup != null) {
//            mGroup.removeAllViewsInLayout();
//        }
    }
}
